import { Table, Card, Pagination, Field, Form, Input, Badge, Box, Button, Select } from '@alifd/next';
import { useRequest } from 'ice';
import { stayQuoteList, alreadyQuoteList, cancelQuote } from '../../service';
import { useFusionTable, useSetState } from 'ahooks';
import styles from './list.module.scss';
import { FormattedDate, FormattedMessage, useIntl } from 'react-intl';
import { getEnumLabel } from '@/utils/enum';
import TableEmptyBlock from '@/components/TableEmptyBlock';
import CategoryService from '@/pages/CommodityCenter/CategoryManage/service';
import BrandService from '@/pages/CommodityCenter/BrandManage/service';
import { SelectRequestConfig } from '@/pages/CommodityCenter/CommodityManage/entity';
import { QuoteStatusEnums } from '@/pages/QuoteManage/CommodityQuote/entity';
import CreateDialog from '../CreateDialog';

interface Props {
  quoted?: boolean;
}

const FilterList: React.FunctionComponent<Props> = ({ quoted }: Props): JSX.Element => {
  const field = Field.useField([]);
  const intl = useIntl();
  const [dialogState, setDialogState] = useSetState({ visible: false, row: {} as any });

  const { paginationProps, tableProps, search, error, refresh } = useFusionTable(
    quoted ? alreadyQuoteList : stayQuoteList,
    {
      field,
    },
  );
  const { submit, reset } = search;

  const { data: brandList, request: brandRequest } = useRequest(BrandService.getBrandPage, SelectRequestConfig);

  const { data: categoryList, request: categoryRequest } = useRequest(CategoryService.getCategoryPage, SelectRequestConfig);

  const onCancel = (id: number) => {
    cancelQuote(id).then(() => {
      refresh();
    });
  };

  return (
    <Card free>
      <Card.Content>
        <Box spacing={20}>
          <Form className="filter-form" responsive fullWidth labelAlign="left" field={field}>
            <Form.Item colSpan={4} label="品牌:" name="brandId">
              <Select
                showSearch
                hasClear
                filterLocal={false}
                onSearch={(val) => brandRequest({ current: 1, pageSize: 10 }, { name: val, enable: true })}
                dataSource={brandList}
                placeholder="输入品牌名称"
              />
            </Form.Item>
            <Form.Item colSpan={4} label="类目:" name="categoryId">
              <Select
                showSearch
                hasClear
                filterLocal={false}
                onSearch={(val) => categoryRequest({ current: 1, pageSize: 10 }, { name: val, enable: true })}
                dataSource={categoryList}
                placeholder="输入类目名称"
              />
            </Form.Item>
            <Form.Item colSpan={4} label="商品名称：">
              <Input name="keywords" hasClear />
            </Form.Item>
            {quoted ? (
              <Form.Item colSpan={4} label="状态:" name="status">
                <Select dataSource={QuoteStatusEnums} hasClear />
              </Form.Item>
            ) : null}
            <Form.Item colSpan={quoted ? 8 : 12} className={styles['form-actions']}>
              <Form.Submit type="primary" onClick={submit} validate style={{ marginRight: '20px' }}>
                <FormattedMessage id="btn.search" />
              </Form.Submit>
              <Form.Reset onClick={reset}><FormattedMessage id="btn.reset" /></Form.Reset>
            </Form.Item>
          </Form>

          <Table
            {...tableProps}
            isZebra
            emptyContent={<TableEmptyBlock error={error} onRefresh={refresh} />}
            primaryKey="id"
          >
            <Table.Column title="Sku编码" dataIndex="id" asyncResizable />
            <Table.Column
              dataIndex="name"
              title="商品信息"
              asyncResizable
              cell={(val, i, row) => (
                <div className={styles.baseinfo}>
                  <img
                    className={styles.img}
                    src={row.mainImage}
                    alt="商品主图"
                  />
                  <div>
                    <span className={styles.title}>{val}</span>
                    <div className={styles.row}>
                      <span>{`${row.brandName}/${row.categoryName}`}</span>
                      <span>{`规格:${row.attrValue || '无'}`}</span>
                    </div>
                  </div>
                </div>
              )}
            />
            <Table.Column
              dataIndex="marketPrice"
              title="市场价"
              asyncResizable
              cell={(val) => intl.formatNumber(val || 0, { style: 'currency', currency: 'USD' })}
            />
            {quoted ? [
              <Table.Column
                dataIndex="askPrice"
                key="askPrice"
                title="报价"
                asyncResizable
                cell={(val) => intl.formatNumber(val || 0, { style: 'currency', currency: 'USD' })}
              />,
              <Table.Column
                dataIndex="storeAmount"
                key="storeAmount"
                title="总库存/剩余"
                asyncResizable
                cell={(val, i, row) => (
                  <p>{`${val}/${row.remainAmount}`}</p>
                )}
              />,
              <Table.Column title="有效期" dataIndex="askPeriod" key="askPeriod" asyncResizable />,
              <Table.Column
                dataIndex="status"
                key="status"
                title="状态"
                align="center"
                asyncResizable
                cell={(val) => (
                  <div>
                    <Badge
                      dot
                      style={{
                        marginRight: 5,
                        backgroundColor: getEnumLabel(QuoteStatusEnums, val, ['value', 'color']),
                      }}
                    />
                    {getEnumLabel(QuoteStatusEnums, val)}
                  </div>
                )}
              />,
              <Table.Column title="报价时间" dataIndex="askTime" key="askTime" asyncResizable cell={(val) => (<FormattedDate value={val} />)} />,
            ]
              : [
                <Table.Column title="当前报价人数" dataIndex="askNum" key="askNum" asyncResizable />,
                <Table.Column title="当前出价人数" dataIndex="bidNum" key="bidNum" asyncResizable />,
                // <Table.Column
                //   title="上架时间"
                //   dataIndex="shippingTime"
                //   key="shippingTime"
                //   asyncResizable
                //   cell={(val) => (<FormattedDate value={val} />)}
                // />,
              ]
            }
            <Table.Column
              dataIndex="opera"
              title="操作"
              cell={(val, i, row) => (
                <Box direction="row" spacing={10} justify="center">
                  <Button type="primary" text onClick={() => setDialogState({ visible: true, row })}>
                    {quoted ? '查看' : '报价'}
                  </Button>
                  {row.status === 1 ? (
                    <Button type="primary" text onClick={() => onCancel(row.id)}>
                      取消
                    </Button>
                  ) : null}
                </Box>
              )}
            />
          </Table>
          <Pagination
            style={{ textAlign: 'right' }}
            shape="arrow-only"
            totalRender={(total) => (
              <FormattedMessage
                id="page.total"
                tagName="div"
                values={{ total }}
              />
            )}
            {...paginationProps}
          />
        </Box>
      </Card.Content>
      <CreateDialog
        visible={dialogState.visible}
        row={dialogState.row}
        onRefresh={refresh}
        onClose={() => setDialogState({ visible: false, row: {} })}
      />
    </Card>
  );
};

export default FilterList;
